package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.AutoScanService;
import freemarker.template.utility.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AutoScanServiceImpl implements AutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private MinIoTemplate minIoTemplate;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;

    //审核文章
    @Override
    public void AutoScanWmNews(Long newsId) throws Exception {
        if (newsId == null) {
            log.warn("文章审核的入参为空");
            return;
        }
        //1.根据newsId查询WmNews信息
        WmNews wmNews = wmNewsMapper.selectById(newsId);
        if (wmNews == null) {
            log.warn("新闻" + newsId + "为空");
            return;
        }
        //2.提取新闻文字
        String title = wmNews.getTitle();
        String content = wmNews.getContent();
        String text = getText(title, content);
        //3.提取新闻图片
        String images = wmNews.getImages();
        List<byte[]> imagesList = getImages(images, content);
        //4.调用阿里云文字审核
        Map textResult = greenTextScan.greeTextScan(text);
        //5.调用阿里云图片审核
        Map imageResult = greenImageScan.imageScan(imagesList);
        //获取审核结果
        Boolean result = getResult(textResult, newsId);
        if (!result) {
            log.warn("文字审核不通过");
            return;
        }
        Boolean result2 = getResult(imageResult, newsId);
        if (!result2) {
            log.warn("图片审核不通过");
            return;
        }

        //6.审核通过ArticleClient远程调用保存文章
        //判断响应码和响应结果
        ArticleDto dto = getDto(wmNews);
        ResponseResult responseResult = articleClient.saveArticle(dto);
        if (responseResult.getCode() != 200 || responseResult.getData() == null) {
            log.warn("文章保存失败");
            return;
        }

        //7.将articleId更新到WmNews表
        Long articleId = (Long) responseResult.getData();
        updateWmNews(newsId, (short) 9, "审核通过", articleId);
    }

    //提取新闻文字 title content
    public String getText(String title, String content) {
        if (StringUtils.isEmpty(content)) {
            return title;
        }
        StringBuilder stringBuilder = new StringBuilder();
        //将content字段转换为map集合
        List<Map> maps = JSON.parseArray(content, Map.class);
        if (!CollectionUtils.isEmpty(maps)) {
            //遍历集合 找到type=text的数据 获取value数据 拼接到一起
            for (Map map : maps) {
                if (CollectionUtils.isEmpty(map)) {
                    continue;
                }
                Object type = map.get("type");
                if ("text".equals(type)) {
                    String value = (String) map.get("value");
                    stringBuilder.append(value);
                }
            }
        }
        //拼接title 转为String
        String s = stringBuilder.append(title).toString();
        return s;
    }

    //提取新闻图片 封面图 内容图
    public List<byte[]> getImages(String images, String content) {
        List<String> list = new ArrayList<>();
        if (!StringUtils.isEmpty(images)) {
            //处理images图片 用,分割字符串 转为list集合
            String[] split = images.split(",");
            List<String> strings = Arrays.asList(split);
            list.addAll(strings);
        }
        if (!StringUtils.isEmpty(content)) {
            //处理content图片 转为map集合
            List<Map> maps = JSON.parseArray(content, Map.class);
            //遍历集合 找到type=image的数据 将value值取出添加到集合中
            for (Map map : maps) {
                if (CollectionUtils.isEmpty(map)) {
                    continue;
                }
                Object type = map.get("type");
                if ("image".equals(type)) {
                    String value = (String) map.get("value");
                    list.add(value);
                }
            }

        }
        //将保存了所有图片的list<String>转为list<byte[]>
        List<byte[]> bytesList = new ArrayList<>();
        for (String image : list) {
            if (StringUtils.isEmpty(image)) {
                continue;
            }
            byte[] bytes = minIoTemplate.downLoadFile(image);
            bytesList.add(bytes);
        }

        return bytesList;
    }

    //获取审核结果
    public Boolean getResult(Map result, Long newsId) {
        if (CollectionUtils.isEmpty(result)) {
            return true;
        }
        String suggestion = (String) result.get("suggestion");
        //block 不通过
        if ("block".equals(suggestion)) {
            updateWmNews(newsId, (short) 2, "不通过", null);
            return false;
        }
        if ("review".equals(suggestion)) {
            updateWmNews(newsId, (short) 3, "需要人工审核", null);
            return false;
        }
        return true;
    }

    //更新WmNews表
    public Boolean updateWmNews(Long newsId, Short status, String reason, Long articleId) {
        WmNews wmNews = new WmNews();
        wmNews.setId(newsId.intValue());
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        if (articleId != null) {
            wmNews.setArticleId(articleId);
        }
        int i = wmNewsMapper.updateById(wmNews);
        if (i < 1) {
            return false;
        }
        return true;
    }

    //构建ArticleDto对象
    public ArticleDto getDto(WmNews wmNews) {
        if (StringUtils.isEmpty(wmNews)) {
            return null;
        }
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, articleDto);
        //补齐参数 频道名称 作者名称 作者id 文章布局
        articleDto.setLayout(wmNews.getType());
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        articleDto.setChannelName(wmChannel.getName());

        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        articleDto.setAuthorId(wmUser.getId().longValue());
        articleDto.setAuthorName(wmUser.getName());
        return articleDto;

    }
}
